package test.excel.workbook;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import test.excel.config.SheetConfig;

public class SheetHeaderReader {
    public SheetHeader readHeader(Sheet sheet, SheetConfig config) {
        checkRowNum(sheet, config);

        SheetHeader header = new SheetHeader();

        Row headerRow = sheet.getRow(config.getStartFrom());

        if (headerRow == null) {
            throw new IllegalStateException("Header row not found at position " + config.getStartFrom());
        }

        for (Cell cell : headerRow) {
            header.addColHeader(cell.getStringCellValue(), cell.getColumnIndex());
        }

        return header;
    }

    private void checkRowNum(Sheet sheet, SheetConfig config) {
        if (config.getStartFrom() > sheet.getLastRowNum()) throw new IllegalStateException("Last row num: " + sheet.getLastRowNum() + ", but start row is " + config.getStartFrom());
    }
}
